package me.alex.lifecycledemo;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * ================================================
 * Description:
 * <p>
 * Created by Alex on 2021/12/31
 * <p>
 * 页面内容介绍:
 * <p>
 * ================================================
 */
public class ServiceLifeObserver implements LifecycleObserver {
    private static final String TAG = ServiceLifeObserver.class.getSimpleName();
    Observable<Long> observable;
    Disposable dis;
    boolean isRun = true;//是否运行  页面暂停的时候不log

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void init() {
        Log.i(TAG, "ON_CREATE");
        Log.i(TAG, "模拟服务业务创建");
        observable = Observable.interval(3, TimeUnit.SECONDS);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void start() {
        Log.i(TAG, "ON_START");
        isRun = true;
        dis = observable.subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (isRun) {
                    Log.e(TAG, "模拟运行,每秒一次");
                }
            }
        });
        Log.i(TAG, "模拟服务业务开始,只会调用一次");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void resume() {
        Log.i(TAG, "ON_RESUME");
        Log.i(TAG, "模拟服务业务重新启动");
        isRun = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void pause() {
        Log.i(TAG, "ON_PAUSE");
        Log.i(TAG, "模拟服务业务暂停");
        isRun = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void stop() {
        Log.i(TAG, "ON_STOP");
        Log.i(TAG, "模拟服务业务停止");
        isRun = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void destroy() {
        Log.i(TAG, "ON_DESTROY");
        if (dis != null) {
            dis.dispose();
            Log.i(TAG, "模拟服务业务销毁");
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any(LifecycleOwner owner) {
        Log.i(TAG, "ON_ANY --- " + owner.getLifecycle().getCurrentState());
    }
}
